// pages/login/login.js
const app = getApp()
import CryptoJS from '../../utils/aes/CryptoJS';
const Crypt = CryptoJS.Crypt
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: "请输入验证码",
    type: true, //true  手机密码登录 false:  手机验证码登录
    // 手机密码登录
    passwordLogin: {
      phone: '',
      password: ''
    },
    // 手机验证码登录
    codeLogin: {
      phone: '',
      code: '',
      key: ''
    },
  },
  // 手机密码登录
  passwordLogin() {
    var postObj = {
      url: '/user/login',
      method: 'POST',
      data: {
        telephone: this.data.passwordLogin.phone,
        password: Crypt(this.data.passwordLogin.password),
        ip: "",
        longitude: wx.getStorageSync('longitude'),
        latitude: wx.getStorageSync('latitude')
      }
    }
    app.request.loginRequest(postObj).then(res => {
      app.success("登陆成功")
      var userId = res.data.data.userId
      var token = res.data.data.token
      wx.setStorageSync('userId', userId)
      wx.setStorageSync('token', token)
      // wx.switchTab({
      //   url: '/pages/chatRoom/chatRoom',
      // })
      wx.navigateBack({
        delta: 2
      })
    }).catch(err => {
      if (!!err.data.data) {
        app.error(app.util.forin(err.data.data))
      } else {
        app.error(err.data.desc)
      }

    })
  },
  // 验证码登录
  codeLogin() {

    if (!!this.data.codeLogin.code && !!this.data.codeLogin.phone) {
      var postObj = {
        url: '/user/captchalogin',
        method: 'POST',
        data: {
          telephone: this.data.codeLogin.phone,
          captcha: this.data.codeLogin.code,
          ip: "",
          longitude: wx.getStorageSync('longitude'),
          latitude: wx.getStorageSync('latitude')
        }
      }
      app.request.loginRequest(postObj).then(res => {
        app.success("登陆成功")
        var userId = res.data.data.userId
        var token = res.data.data.token
        wx.setStorageSync('userId', userId)
        wx.setStorageSync('token', token)
        // wx.switchTab({
        //   url: '/pages/chatRoom/chatRoom',
        // })
        wx.navigateBack({
          delta: 2
        })
      }).catch(err => {
        if (!!err.data.data) {
          app.error(app.util.forin(err.data.data))
        } else {
          app.error(err.data.desc)
        }
      })
    } else {
      app.error("不能为空哦!")
    }


  },
  // 短信验证码接口
  getCode() {
    if (this.data.time == "请输入验证码") {
      if (!!this.data.codeLogin.phone && this.data.codeLogin.phone.length == 11) {
        var postObj = {
          url: '/user/captcha',
          method: 'POST',
          data: {
            telephone: this.data.codeLogin.phone,
            captchaType: "login"
          }
        }
        app.request.noLoginRequest(postObj).then(res => {
          console.log('短信验证码接口res', res)
          app.success("发送成功")
          this.start()
          console.log(res.data.data)
        }).catch(err => {
          console.log('短信验证码接口err', err)
        })
      } else {
        app.error("号码规格错误")
      }
    } else {
      app.error("请勿频繁操作！")
    }

    // this.start()

  },
  start() {
    this.reset();
    const countDown = this.selectComponent('.control-count-down');
    countDown.start();

  },
  reset() {
    const countDown = this.selectComponent('.control-count-down');
    countDown.reset();
  },
  finished() {
    // this.reset();
    // this.setData({
    //   time: "请输入验证码"
    // })
  },
  onChangetime(e) {
    // console.log(e.detail)
    if (e.detail.seconds == 0 && e.detail.milliseconds == 0) {
      this.setData({
        time: "请输入验证码"
      })
    } else if (e.detail.seconds == 60 && e.detail.milliseconds == 0) {
      this.setData({
        time: "请输入验证码"
      })
    } else {
      this.setData({
        time: e.detail.seconds
      })
    }
  },
  onChangepasswordLoginphone(event) {
    var phone = event.detail
    this.setData({
      [`passwordLogin.phone`]: phone
    })
  },
  onChangepasswordLoginpassword(event) {
    var password = event.detail
    this.setData({
      [`passwordLogin.password`]: password
    })
  },
  onChangecodeLoginphone(event) {
    var phone = event.detail
    this.setData({
      [`codeLogin.phone`]: phone
    })
  },
  onChangecodeLogincode(event) {
    var code = event.detail
    this.setData({
      [`codeLogin.code`]: code
    })
  },
  // 切换登录方式
  changetype() {


    var passwordLogin = {
      phone: '',
      password: ''
    }
    var codeLogin = {
      phone: '',
      code: '',
      key: ''
    }
    this.setData({
      type: !this.data.type,
      passwordLogin: passwordLogin,
      codeLogin
    })
  },
  loginNo() {
    // wx.switchTab({
    //   url: '/pages/chatRoom/chatRoom',
    // })

    wx.switchTab({
      url: '/pages/game/gameIndex/gameIndex',
    })
  },
  //定位方法

  getUserLocation: function () {
    var _this = this;
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //未授权
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
                wx.setStorageSync('latitude', "")
                wx.setStorageSync('longitude', "")
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      _this.geo();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //用户首次进入页面,调用wx.getLocation的API
          _this.geo();
        } else {
          console.log('授权成功')
          //调用wx.getLocation的API
          _this.geo();
        }
      }
    })
  },
  // 获取定位城市

  geo: function () {
    var _this = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        wx.setStorageSync('latitude', latitude)
        wx.setStorageSync('longitude', longitude)
      },
      fail: function (err) {
        wx.setStorageSync('latitude', "")
        wx.setStorageSync('longitude', "")
      }
    })
  },

  toRegister() {
    wx.navigateTo({
      url: '/pages/register/register',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //检查录音权限
    app.util.checkPermission()
    this.getUserLocation()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})